package com.siemens.industrial.web.mvc.service.admin;

import com.siemens.industrial.model.admin.Device;
import com.siemens.industrial.utils.GlobalResponseCode;
import com.siemens.industrial.utils.SiemensException;
import com.siemens.industrial.web.mvc.dao.admin.DeviceDao;
import com.siemens.industrial.web.mvc.dao.admin.TenantDao;
import com.siemens.industrial.web.mvc.pojo.DataTableQuery;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by qupen on 2016/8/31.
 */
@Service
public class DeviceService {
    @Resource
    DeviceDao deviceDao;

    @Resource
    TenantDao tenantDao;

    @Resource
    JdbcTemplate jdbcTemplate;

    public Device getDeviceById(String deviceId) {
        return deviceDao.findOneById(deviceId);
    }

    public Device getDeviceByUniqueId(String deviceUniqueId) {
        return deviceDao.findOneByUniqueId(deviceUniqueId);
    }

    public List<Device> getDevices() {
        return deviceDao.getDeviceList();
    }

    @Transactional
    public void saveDevice(Device device) throws SiemensException {
        if (deviceDao.findOneByUniqueId(device.getDeviceUniqueId()) == null) {
            deviceDao.save(device);
        } else {
            throw new SiemensException(GlobalResponseCode.ERROR_DEVICE_EXISTED);
        }
    }

    @Transactional
    public void updateDevice(String deviceId) throws SiemensException {
        if (deviceDao.findOneById(deviceId) != null) {
            deviceDao.updateById(deviceId);
        } else {
            throw new SiemensException(GlobalResponseCode.ERROR_DEVICE_NOT_EXISTED);
        }
    }

    public int getDeviceConut(String tenantId) {
        return deviceDao.getDeviceCountByTenantId(tenantId);
    }

    //dataTable search getWay status list
    public Map<String,Object> getGetWayStatusByDataTable(HttpServletRequest request){
        DataTableQuery dt = new DataTableQuery(request);
        List<Map<String, Object>> list = new ArrayList<>();

        String totalSql = "SELECT COUNT(1) FROM `siemens`.gateway_state where 1=1 ";
        String totalSqlWhereGroup = " group by version,clientId ";
        String sql = "Select * from `siemens`.gateway_state where 1=1";
        int total = jdbcTemplate.queryForList(totalSql + totalSqlWhereGroup).size();
        int filteredCount = total;
        if (!dt.getSearch().equals("")) {
            String search = " and (`clientId` like '%" + dt.getSearch() + "%' or `version` like '%" + dt.getSearch() + "%' or `time` like '%" + dt.getSearch() + "%')";
            sql += search;
            filteredCount = jdbcTemplate.queryForList(totalSql + search + totalSqlWhereGroup).size();
        }

        if (!dt.getOrderDBColumn().equals("") && !dt.getOrderAscOrDesc().equals("")) {
            String order = " ORDER BY `" + dt.getOrderDBColumn() + "` " + dt.getOrderAscOrDesc();
            sql += order;
        }

        sql += totalSqlWhereGroup;
        String limit = " limit " + dt.getStart() + "," + dt.getLength();
        sql += limit;

        list = jdbcTemplate.queryForList(sql);
        return dt.buildResponse(filteredCount, total, list);
    }

    public Map<String, Object> getAllHeaderData() {
        List<Map<String, Object>> groups = deviceDao.getGroups();
        List<Map<String, Object>> lines = deviceDao.getLines();
        List<Map<String, Object>> types = deviceDao.getTypes();
        List<Map<String, Object>> models = deviceDao.getModels();
        List<Map<String, Object>> tenantNames = deviceDao.getTenantNames();

        return new HashMap<String, Object>() {{
            put("groups", groups);
            put("lines", lines);
            put("types", types);
            put("models", models);
            put("tenantNames", tenantNames);
        }};
    }

    public List<Map<String, Object>> getAllTenantNames() {
        return deviceDao.getTenantNames();
    }

    public Map<String, Object> getAllHeaderDataByTenantId(String tenantId) {
        List<Map<String, Object>> groups = deviceDao.getGroupsByTenantId(tenantId);
        List<Map<String, Object>> lines = deviceDao.getlinesByTenantId(tenantId);
        List<Map<String, Object>> types = deviceDao.getTypesByTenantId(tenantId);
        List<Map<String, Object>> models = deviceDao.getModelsByTenantId(tenantId);
        List<Map<String, Object>> mtIds = deviceDao.getMTIdByTenantId(tenantId);

        return new HashMap<String, Object>() {{
            put("groups", groups);
            put("lines", lines);
            put("types", types);
            put("models", models);
            put("MTIds", mtIds);
        }};
    }

    public List<Map<String, Object>> search(String tenantId, String model, String type, String group, String line) {
        String sql = "select * from `siemens`.`device` where 1=1";
        if (!tenantId.equals("")) {
            sql += " and `tenant_id` ='" + tenantId + "'";
        }
        if (!model.equals("")) {
            sql += " and `device_model` ='" + model + "'";
        }
        if (!type.equals("")) {
            sql += " and `device_type` ='" + type + "'";
        }
        if (!group.equals("")) {
            sql += " and `group` ='" + group + "'";
        }
        if (!line.equals("")) {
            sql += " and `line` ='" + line + "'";
        }

        String innerSql = "select a.*,b.tenant_name from ("+sql+") a inner join `siemens`.tenant b on a.tenant_id = b.tenant_id order by a.device_unique_id;";
        System.out.print(innerSql);

        return deviceDao.searchBySql(innerSql);
    }

    public Map<String, Object> getAdminAlertData(String model,String type) {
        List<Map<String, Object>> mtids = deviceDao.getDeviceMTIdByModelAndType(model, type);
        List<Map<String, Object>> groups = deviceDao.getDeviceGroupsByModelAndType(model, type);
        List<Map<String, Object>> lines = deviceDao.getDeviceLinesByModelAndType(model, type);

        return new HashMap<String, Object>() {{
            put("mtids", mtids);
            put("groups", groups);
            put("lines", lines);
        }};
    }
}
